import { useDispatch, useSelector } from 'react-redux';
import { CapsuleTabs, Input, Popup,Form,DatePicker} from 'antd-mobile';
import { useEffect, useState, useRef} from 'react';
// import { getBilltype } from '../../store/modules/bookicon'
import { NumberKeyboard, Button, DatePickerView,Modal } from 'antd-mobile'
import './index.css'
import dayjs from 'dayjs';
import {request} from '../../utils'
import { message } from 'antd';


function PopupAddBills({visible,setVisible,id,amount,time,setAmount,setTime,setId,now,loadMore}) {

    const dispatch = useDispatch()
    const [timevisible, setTimevisible] = useState(false)
    
    const billtype = useSelector(state => state.billtype.billtype)
    const [textvisible, setTextvisible] = useState(false)
    const [remark,setRemark]  = useState('')
    const handleSubmit =async () => { 
            const formdata = new FormData()
            formdata.append('bill_type_id', id)
            formdata.append('amount', +amount)
            formdata.append('bill_time', time)
            formdata.append('remark', remark)
            if(formdata.get('bill_type_id') === ''){
                Modal.show({
                    content: '请选择类型',
                    closeOnMaskClick: true,
                })
            }else{
                try{
                    await request.post('api/auth/bills', formdata)
                    await loadMore(true)
                }catch(err){
                    Modal.show({
                        content: err.message,
                        closeOnMaskClick: true,
                    })
                }
            
            setVisible(false)
          }
        
        setVisible(false)
    }
    const remarkref = useRef(null)
    const resetForm = () => {
        setId('');         // 重置账单类型ID
        setAmount('');     // 重置金额
        setTime(dayjs(now).format('YYYY-MM-DD HH:mm:ss')); // 重置时间
        setRemark('');     // 重置备注
        setTextvisible(false); // 关闭备注弹窗
        
      };
    
      // 当弹窗关闭时重置状态
      useEffect(() => {
        if (!visible) {
          resetForm();
        }
      }, [visible]); // 监听 visible 变化
    return (
        <>
        <Popup 
            visible={visible}
            onMaskClick={() => {
                setVisible(false)
              }}
        >
            <div style={{width:'100%',height:'400px'}}>
                
                

                <CapsuleTabs >
                <CapsuleTabs.Tab title='收入' key='income' >
                    <div style={{marginBottom:'5px',color:'#999',display:'flex',justifyContent:'space-between'}}><span onClick={() => setTimevisible(true)}>{`日期：${time?dayjs(time).format('YYYY-MM-DD'):dayjs(now).format('YYYY-MM-DD')}`}</span><span onClick={() => setTextvisible(true)}>添加备注</span></div>
                    <div className='type'>
                        <div style={{display:'flex'}}>
                            {billtype?.map((item, index) => {
                                    if (item.flow === 'income') {
                                        return (
                                            <Button className='type'  style={{overflow:'hidden',backgroundColor: id === item.id ? '#eee' : 'transparent' }} fill='none' onClick={() => {
                                                setId(item.id)
                                                }}>
                                                <div dangerouslySetInnerHTML={{__html:item.icon.replace('<svg', '<svg width="30px" height="30px"')}}></div>
                                                <div className='name'>{item.name}</div>
                                            </Button>
                                                
                                        )
                                    }
                                })}
                        </div>
                        
                    </div>
                        
                    
                    </CapsuleTabs.Tab>
                    <CapsuleTabs.Tab title='支出' key='outcom' >
                    <div style={{marginBottom:'5px',color:'#999',display:'flex',justifyContent:'space-between'}}><span onClick={() => setTimevisible(true)}>{`日期：${time?dayjs(time).format('YYYY-MM-DD'):dayjs(now).format('YYYY-MM-DD')}`}</span><span onClick={() => setTextvisible(true)}>添加备注</span></div>
                    <div className='type'>
                        <div style={{display:'flex'}}>
                            {billtype?.map((item, index) => {
                                    if (item.flow === 'outcome') {
                                        return (
                                            <Button className='type'  style={{overflow:'hidden',backgroundColor: id === item.id ? '#eee' : 'transparent' }} fill='none' onClick={() => {
                                                setId(item.id)
                                                }}>
                                                <div dangerouslySetInnerHTML={{__html:item.icon.replace('<svg', '<svg width="30px" height="30px"')}}></div>
                                                <div className='name'>{item.name}</div>
                                            </Button>
                                                
                                        )
                                    }
                                })}
                        </div>
                        
                    </div>
                        
                    
                    </CapsuleTabs.Tab>
                </CapsuleTabs>
                <Input placeholder='输入今日收获吧' value = {amount} clearable />
                <NumberKeyboard
                    visible={!timevisible&&visible&&!textvisible}
                    onInput={(key) => {
                        const  newNum = amount + key
                        setAmount(newNum)
                    }}
                    onDelete={() => {
                        const newNum = amount.slice(0, -1)
                        setAmount(newNum)
                    }}
                    showCloseButton={false}
                    confirmText='确定'
                    onConfirm={handleSubmit}
                    customKey={'.'}
                />
            </div>
            
        </Popup>
        
        <DatePicker
            title="选择日期"
            visible={timevisible}
            defaultValue={now}
            onClose={() => setTimevisible(false)}
            onConfirm={value => {
                setTime(dayjs(value).format('YYYY-MM-DD HH:mm:ss'))
                setTimevisible(false)
            }}
            />
        <Popup
        visible={textvisible}
        onMaskClick={() => {
            setTextvisible(false)
        }}
        bodyStyle={{ height: '40vh' }}
        >
            <Form
            ref={remarkref}
            footer={
                <Button block type='submit' color='primary' size='large'>
                    确定
                </Button>
                }
            onFinish={(values) => {
                setTextvisible(false)
                setRemark(values.name)
                remarkref.current.resetFields(); // 重置备注输入框
            }}
            >
                <Form.Item name='name' label='备注'>
                    <Input  placeholder='请输入备注' />
                </Form.Item>
            </Form>
        </Popup>
    </>
        
    )
}
export default PopupAddBills